import pygame

from daxiong.const import SIZE


class HeroSprite(pygame.sprite.Sprite):
    def __init__(self, speed=20):
        super().__init__()
        self.image_left = pygame.image.load("./image/hero.jpeg")
        self.image_right = pygame.transform.flip(self.image_left, True, False)
        self.image = self.image_left
        self.rect = self.image.get_rect()
        self.rect.center = (SIZE[0] / 2, SIZE[1] - 100)
        self.speed = speed

    def update(self):
        key_pressed = pygame.key.get_pressed()
        if key_pressed[pygame.K_LEFT] or key_pressed[pygame.K_a]:
            if self.image is not self.image_left:
                self.image = self.image_left
            self.rect.left -= self.speed
            if self.rect.left <= 0:
                self.rect.left = 0
        if key_pressed[pygame.K_RIGHT] or key_pressed[pygame.K_d]:
            if self.image is not self.image_right:
                self.image = self.image_right
            self.rect.right += self.speed
            if self.rect.right >= SIZE[0]:
                self.rect.right = SIZE[0]
        if key_pressed[pygame.K_UP] or key_pressed[pygame.K_w]:
            self.rect.top -= self.speed
            if self.rect.top <= 0:
                self.rect.top = 0
        if key_pressed[pygame.K_DOWN] or key_pressed[pygame.K_s]:
            self.rect.bottom += self.speed
            if self.rect.bottom >= SIZE[1]:
                self.rect.bottom = SIZE[1]


class HeroManage:
    def __init__(self, gm):
        self.hero_group = pygame.sprite.Group()
        self.hero = HeroSprite()
        self.hero.add(self.hero_group)
        self.gm = gm

    def update(self):
        if self.gm.state == "gaming":
            self.hero_group.draw(self.gm.screen)
            self.hero_group.update()
